# coding:utf-8
from django.views.generic import ListView,DetailView
from django.views.generic.edit import CreateView,UpdateView,DeleteView
from django.shortcuts import render, redirect
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from django.http import JsonResponse
from django.core import serializers
from django.core.paginator import Paginator
from django.contrib.auth.decorators import login_required,permission_required
from .models import Students, Grades
import os
import json
from datetime import datetime
from .forms import StudentForm
# Create your views here.

# 显示学生信息,分页显示

class StudentListView(ListView):
    model = Students
    template_name = "student/StudentList.html"
    paginate_by = 10
    context_object_name = "students"
    def get_context_data(self,*args,**kwargs):
        context = super(StudentListView,self).get_context_data(**kwargs)
        context['grades'] = Grades.objects.all()
        return context

class StudentCreateView(CreateView):
    model = Students
    form_class = StudentForm

# 查询学生信息
@login_required(login_url='/loginurl/')
def getbyname(request):
    # 错误：字典对象不可调用,原因request获得的对象是一个字典对象,错误在于  request.GET('name')
    #更正为 request.GET['name']
    t_name=request.GET['tName']
    student=Students.objects.filter(name=t_name)
    gradelist = Grades.objects.all()
    content={"studentdata":student,
             "gradedata":gradelist,
             }
    return render(request,'student/ShowStudent.html',content)

@login_required(login_url='/loginurl/')
def getbyid(request,stu_id):
    student=Students.objects.filter(student_id=stu_id)
    content={"studentdata":student}
    return render(request,'student/update.html',content)

@login_required(login_url='/loginurl/')
def getbygrade(request):
    gra_id=request.GET['tGrade']
    grade= Grades.objects.filter(grade_id=gra_id).first()
    '''在一对多关系的表中可以用grade.student_set来获取这个班级的所有学生,反过来可以用student.gra_id.name来获取
    该学生所对应班级的名称'''
    studentlist = grade.students_set.all()
    gradelist = Grades.objects.all()
    content={"studentdata":studentlist,
             "gradedata":gradelist,
             }
    return render(request,'student/ShowStudent.html',content)

# 增加学生信息
@login_required(login_url='/loginurl/')
def add_page( request ):
    grades= Grades.objects.all()
    content= {"gradedata":grades}
    return render(request, 'student/add.html',content)

@csrf_exempt
@login_required(login_url='/loginurl/')
@permission_required('AppStudent.add_students',login_url='/nopermisson/')
def add_student(request):
    t_id = request.POST['tId']
    t_name = request.POST['tName']
    t_age = request.POST['tAge']
    t_sex = request.POST['tSex']
    t_graid = request.POST['tGraid']
    t_image = request.FILES['tImage'] #上传文件UploadedFile对象
    image_name=datetime.now().strftime('%Y%m%d%H%M%S%f') + t_image.name
    fname = os.path.join(settings.MEDIA_ROOT, image_name)
    with open(fname, 'wb') as pic:
        for c in t_image.chunks(): #UploadedFile.chunks()：如果上传的文件足够大需要分块返回
            pic.write(c)

    student=Students()
    student.student_id=t_id
    student.name=t_name
    student.age=t_age
    student.sex=t_sex
    #通过Django操作数据库时，不需要写sql语句，通过模型操作数据库传值无法成功，其原因是因为orderlist表中的uid关联User表中的uid（主键），
    # 通过Django进行增操作时，Orderlist.uid需要一个User的实例（外键约束）
    # 使用Django模型对数据库操作时，如有依赖关系，则参数的值也需要为一个对象，或查询到的外键是一个对象
    grade= Grades.objects.filter(grade_id=t_graid).first()
    student.gra_id = grade
    # 存访问路径到数据库
    student.image = os.path.join("/static/media/", image_name)
    student.save()
    return redirect('/show_student/')

# 删除学生信息
@csrf_exempt
@login_required(login_url='/loginurl/')
def delete_student(request,stu_id):
    Students.objects.filter(student_id=stu_id).delete()
    return redirect('/show_student/')

# 更新学生信息
@csrf_exempt
@login_required(login_url='/loginurl/')
def update_student(request):
    t_id=request.POST['tId']
    t_name = request.POST['tName']
    t_age = request.POST['tAge']
    t_sex = request.POST['tSex']
     # 缺陷：文件必传
    t_image = request.FILES['tImage']
    fname = os.path.join(settings.MEDIA_ROOT, t_image.name)
    with open(fname, 'wb') as pic:
        for c in t_image.chunks():
            pic.write(c)
    t_image = os.path.join("/static/media/", t_image.name)

    Students.objects.filter(student_id=t_id).update(name=t_name,age=t_age,sex=t_sex,image=t_image)

    return redirect('/show_student/')


#add_grade接受一个get请求，往数据库添加一条grade数据
@require_http_methods(['GET'])
def add_grade(request):
    response = {}
    try:
        name = request.GET.get('name')
        gra_id = request.GET.get('grade_id')
        boys = request.GET.get('boys_num')
        girls = request.GET.get('girls_num')
        content = request.GET.get('content')
        teacher_id = request.GET.get('class_teacher')
        grade = Grades(name=name,grade_id=gra_id,boys_num=boys,girls_num=girls,content=content,class_teacher=teacher_id)
        grade.save()
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)


@require_http_methods(['GET'])
def show_grades(request):
    response = {}
    try:
        grades = Grades.objects.filter()
        response['list'] = json.loads(serializers.serialize('json',grades))
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)




